﻿#include "Thread.h"
#include "Mutex.h"
#include "Tracer.h"
using namespace libemb;

#include <sched.h>

static MutexLock lock;
static sint32 g_var =0;

static MutexCond cond(&lock);

class ProgramA :public Runnable{
public:
	void run()
	{
		while(1)
		{
			lock.lock();
			TRACE_DBG_CLASS("AAAAAAAAAAAAAAAAAAA is running.\n");
			//sleep(1);
			g_var++;
            if (g_var==10)
            {
                TRACE_DBG_CLASS("AAAAAAAAAAAAAAAAAAA meet.\n");
                cond.meet();
            }
			lock.unLock();
			sleep(1);/* 一定要加这个sleep,否则其他线程可能永远拿不到锁 */
		}
	}
};


class ProgramB :public Runnable{
public:
	void run()
	{
		while(1)
		{
			lock.lock();
			TRACE_DBG_CLASS("BBBBBBBBBBBBBBBBBBBB is waiting.\n");
			//sleep(1);
			int ret= cond.wait(5);
			if(ret!=STATUS_OK)
			{
				TRACE_ERR_CLASS("BBBBBBBBBBBBBBBBBBBB waited ret=%d\n",ret);
			}
            TRACE_DBG_CLASS("BBBBBBBBBBBBBBBBBBBB waited\n");
			lock.unLock();
			sleep(1);
		}
	}
};

void TestThread()
{
	ProgramA progA;
	ProgramB progB;
	Thread threadA,threadB;
	threadA.start(&progA);
	threadB.start(&progB);
	while(1)
	{
		TRACE_DBG("Thread Test is running----------\n");
		sleep(5);
        if(threadA.cancel())
        {
            TRACE_DBG("Thread A cancel OK.\n");
            if(threadB.cancel())
            {
                TRACE_DBG("Thread B cancel OK.\n");
                break;
            }
            else
            {
                TRACE_ERR("Thread B cancel failed.\n");
            }  
        }
        else
        {
            TRACE_ERR("Thread A cancel failed.\n"); 
        }
        
	}
}


class TaskCreator:Runnable{
public:
    TaskCreator()
    {
        m_mainThread.start(this);
    }
    void task01(void* arg)
    {
        while(1)
        {
            printf("task run......\n");
            
            if (m_stopFlag==0)
            {
                printf("0000000000000--addr:%x\n",&m_stopFlag);
            }
            else
            {
                printf("11111111111111--addr:%x\n",&m_stopFlag);
            }

            sleep(1);
        }
    }
    void run()
    {
        int i=0;
       m_mainThread.createTask(this, task_selector(TaskCreator::task01),NULL);
       while(1)
        {
            printf("main thread run......addr:%x\n",&m_stopFlag);
            sleep(1);
            i++;
            if (i>5)
            {
                m_stopFlag = 1;  
            }
        } 
    }
private:
    Thread m_mainThread;
    int m_stopFlag;
};

void TestTask()
{
    TaskCreator* test=NEW_OBJ TaskCreator();    
	while(1)
    {	
        sleep(1);
	}
	return;
}


